package com.fsck.k9.accounts;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

import com.fsck.k9.accounts.R;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class Import extends Activity {
	private static final int DIALOG_PROGRESS = 1;
    private int maxProgress=0;
	
	private ArrayList<Account> accounts=new ArrayList<Account>();
    private ProgressDialog mProgressDialog;
    private int mProgress;
    private Handler mProgressHandler;
	protected int currentCheckedItem;
	HashMap<String,Properties> propertiesFromUuid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.import_export);

    	this.propertiesFromUuid=new HashMap<String,Properties>();

		File directory=new File(Main.STORAGE_LOCATION);
		File[] files=directory.listFiles();
		if(files!=null)
		{
			for(File file:files)
			{
				String[] tokens = file.getName().split("\\.");
				if(file.length()>0)
				{
			        String uUid = tokens[0];
					Properties db=new Properties();
			        try {
			        	FileInputStream in=new FileInputStream(file);
			        	db.loadFromXML(in);
			        	in.close();
				        this.propertiesFromUuid.put(uUid, db);
				        this.accounts.add(new Account(db.getProperty(uUid+ ".description"),uUid,0));
					} catch (InvalidPropertiesFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

        ListView accountsList = (ListView) findViewById(R.id.accounts);
        
        accountsList.setItemsCanFocus(false);
        accountsList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        if(this.accounts.size()>0)
        {
    		accountsList.setSelection(this.accounts.size());
		
	        ArrayAdapter<Account> adapter = new ArrayAdapter<Account>(this, android.R.layout.simple_list_item_multiple_choice, (Account[]) this.accounts.toArray(new Account[1]));
	        accountsList.setAdapter(adapter);
        }
        ((Button)findViewById(R.id.doIt)).setText(R.string.import_string);        
 
        mProgressHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (mProgress >= Import.this.maxProgress) {
                    mProgressDialog.dismiss();
                    Import.this.finish();
                } else {
                    ListView accountsList = (ListView) findViewById(R.id.accounts);
                    long ids[]=accountsList.getCheckItemIds();
                    while(Import.this.currentCheckedItem<ids.length && accountsList.isItemChecked((int)ids[Import.this.currentCheckedItem])==false)
                		Import.this.currentCheckedItem++;

                    Account account= (Account) accountsList.getItemAtPosition((int)ids[Import.this.currentCheckedItem]);
                   	ContentResolver cr = getBaseContext().getContentResolver();
        			ContentValues values = new ContentValues(1);
                	Properties db=Import.this.propertiesFromUuid.get(account.getUuid());
                	try {
        				ByteArrayOutputStream bytes=new ByteArrayOutputStream();
    					db.storeToXML(bytes, "Account read by k9accounts");
    	                bytes.flush();
        				values.put("xmlAccount", bytes.toString());
    					Uri uri=Uri.parse("content://com.fsck.k9.accountprovider/write/"+account.getUuid()+"/");
    	    			cr.insert(uri, values);
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
                   	Import.this.currentCheckedItem++;
                   	mProgress++;
                    mProgressDialog.incrementProgressBy(1);
                    mProgressHandler.sendEmptyMessageDelayed(0, 100);
                }
            }
        };

        
        this.findViewById(R.id.doIt).setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub
    			Import.this.maxProgress=0;
    			Import.this.currentCheckedItem=0;
                ListView accountsList = (ListView) findViewById(R.id.accounts);
                long ids[]=accountsList.getCheckItemIds();
                for(int pos=0; pos<ids.length;pos++)
                {
                	if(accountsList.isItemChecked((int)ids[pos]))
                		maxProgress++;
                }

                showDialog(DIALOG_PROGRESS);
                mProgress = 0;
                mProgressDialog.setProgress(0);
                mProgressHandler.sendEmptyMessage(0);
                
    		}
            });
        this.findViewById(R.id.SelectAll).setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub
                ListView accountsList = (ListView) findViewById(R.id.accounts);
                for(int pos=0; pos<accountsList.getCount();pos++)
                	accountsList.setItemChecked(pos, true);
    		}
            });
        this.findViewById(R.id.UnselectAll).setOnClickListener(new OnClickListener() {
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub
                ListView accountsList = (ListView) findViewById(R.id.accounts);
                for(int pos=0; pos<accountsList.getCount();pos++)
                	accountsList.setItemChecked(pos, false);
    		}
            });
     }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_PROGRESS:
            mProgressDialog = new ProgressDialog(Import.this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMax(this.maxProgress);
            return mProgressDialog;
        }
		return null;
    }
 }
